Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
!conda install --yes -c menpo dlib 
Collecting package metadata: done
Solving environment: done


==> WARNING: A newer version of conda exists. <==
  current version: 4.6.14
  latest version: 4.7.11

Please update conda by running

    $ conda update -n base conda



## Package Plan ##

  environment location: /opt/conda

  added / updated specs:
    - dlib


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    _libgcc_mutex-0.1          |             main           3 KB  defaults
    ca-certificates-2019.6.16  |       hecc5488_0         145 KB  conda-forge
    certifi-2019.6.16          |           py36_1         149 KB  conda-forge
    dlib-19.10                 |py36_blas_openblas_200         2.3 MB  conda-forge
    numpy-1.12.1               |py36_blas_openblash24bf2e0_201         8.6 MB  conda-forge
    openblas-0.2.20            |                8        17.0 MB  conda-forge
    openssl-1.0.2r             |       h14c3975_0         3.1 MB  conda-forge
    scipy-1.1.0                |py36_blas_openblash7943236_201        40.3 MB  conda-forge
    ------------------------------------------------------------
                                           Total:        71.6 MB

The following NEW packages will be INSTALLED:

  _libgcc_mutex      pkgs/main/linux-64::_libgcc_mutex-0.1-main
  dlib               conda-forge/linux-64::dlib-19.10-py36_blas_openblas_200

The following packages will be REMOVED:

  librosa-0.5.1-py36_1
  libtorch-0.1.12-nomkl_0
  nltk-3.2.5-py_0
  pymc3-3.2-py36_0
  scikit-learn-0.19.1-py36_blas_openblas_200
  seaborn-0.8.1-py36_0

The following packages will be UPDATED:

  ca-certificates                               2017.11.5-0 --> 2019.6.16-hecc5488_0
  certifi                                  2017.11.5-py36_0 --> 2019.6.16-py36_1
  numpy                       1.12.1-py36_blas_openblas_200 --> 1.12.1-py36_blas_openblash24bf2e0_201
  openblas                                         0.2.19-2 --> 0.2.20-8
  openssl                                          1.0.2n-0 --> 1.0.2r-h14c3975_0
  scipy                       0.19.1-py36_blas_openblas_202 --> 1.1.0-py36_blas_openblash7943236_201



Downloading and Extracting Packages
numpy-1.12.1         | 8.6 MB    | ##################################### | 100% 
_libgcc_mutex-0.1    | 3 KB      | ##################################### | 100% 
openblas-0.2.20      | 17.0 MB   | ##################################### | 100% 
ca-certificates-2019 | 145 KB    | ##################################### | 100% 
scipy-1.1.0          | 40.3 MB   | ##################################### | 100% 
dlib-19.10           | 2.3 MB    | ##################################### | 100% 
openssl-1.0.2r       | 3.1 MB    | ##################################### | 100% 
certifi-2019.6.16    | 149 KB    | ##################################### | 100% 
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
In [5]:
!conda install --yes -c anaconda scikit-learn
Collecting package metadata: done
Solving environment: done


==> WARNING: A newer version of conda exists. <==
  current version: 4.6.14
  latest version: 4.7.11

Please update conda by running

    $ conda update -n base conda



## Package Plan ##

  environment location: /opt/conda

  added / updated specs:
    - scikit-learn


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    ca-certificates-2019.5.15  |                1         134 KB  anaconda
    certifi-2019.6.16          |           py36_1         156 KB  anaconda
    openssl-1.0.2s             |       h7b6447c_0         3.1 MB  anaconda
    scikit-learn-0.19.0        |   py36h97ac459_2         5.2 MB  anaconda
    ------------------------------------------------------------
                                           Total:         8.6 MB

The following NEW packages will be INSTALLED:

  scikit-learn       anaconda/linux-64::scikit-learn-0.19.0-py36h97ac459_2

The following packages will be UPDATED:

  openssl            conda-forge::openssl-1.0.2r-h14c3975_0 --> anaconda::openssl-1.0.2s-h7b6447c_0

The following packages will be SUPERSEDED by a higher-priority channel:

  ca-certificates    conda-forge::ca-certificates-2019.6.1~ --> anaconda::ca-certificates-2019.5.15-1
  certifi                                       conda-forge --> anaconda



Downloading and Extracting Packages
scikit-learn-0.19.0  | 5.2 MB    | ##################################### | 100% 
openssl-1.0.2s       | 3.1 MB    | ##################################### | 100% 
certifi-2019.6.16    | 156 KB    | ##################################### | 100% 
ca-certificates-2019 | 134 KB    | ##################################### | 100% 
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
In [6]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('/data/dog_images/train')
valid_files, valid_targets = load_dataset('/data/dog_images/valid')
test_files, test_targets = load_dataset('/data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("/data/dog_images/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [7]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("/data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [8]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [9]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

human images: %100.0, dog images: %11.0

In [20]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.
## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
hum_pos = np.mean([face_detector(img_path) for img_path in human_files_short])
hum_neg = np.mean([face_detector(img_path) for img_path in dog_files_short])
print(f"human prediction acc: %{hum_pos * 100}, dog prediction acc: %{hum_neg * 100}")
human prediction acc: %100.0, dog prediction acc: %11.0

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: There are many techniques for detecting objects in image detecting face can be a special case from object detection, we may use different algorithms I found that Histogram of oriented gradients(HOG), R-CNN, FaceNet, YOLO may work better in localizing the face in the image, with different angles.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [10]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.
import cv2
import dlib
# extract pre-trained face detector
f_detector = dlib.get_frontal_face_detector()
f_predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = f_detector(img)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for face in faces:
    landmarks = f_predictor(img, face)
    for point in range(68):
        x = landmarks.part(point).x
        y = landmarks.part(point).y
        cv2.circle(img, (x, y), 1, (0, 255, 0), -1)
    pt1 = (face.left(), face.top())
    pt2 = (face.right(), face.bottom())
    cv2.rectangle(img, pt1, pt2, color=(0, 255, 0), thickness=2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1
In [11]:
# returns "True" if face is detected in image stored at img_path
def my_face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = f_detector(gray)
    return len(faces) > 0
In [23]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.
## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
hum_pos = np.mean([my_face_detector(img_path) for img_path in human_files_short])
hum_neg = np.mean([my_face_detector(img_path) for img_path in dog_files_short])
print(f"human prediction acc: %{hum_pos * 100}, dog prediction acc: %{hum_neg * 100}")
human prediction acc: %100.0, dog prediction acc: %6.0

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [12]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5
102858752/102853048 [==============================] - 3s 0us/step

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [13]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [14]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [15]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

dog prediction acc: %100.0, human prediction acc: %0.0

In [28]:
### TODO: Test the performance of the dog_detector function
# dog_imgs = paths_to_tensor(dog_files_short)
# ResNet50_predict_labels()
### on the images in human_files_short and dog_files_short.
dog_pos = sum([dog_detector(img_path) for img_path in dog_files_short]) / len(dog_files_short)
dog_neg = sum([dog_detector(img_path) for img_path in human_files_short]) / len(dog_files_short)
print(f"dog prediction acc: %{dog_pos* 100}, human prediction acc: %{dog_neg * 100}")
dog prediction acc: %100.0, human prediction acc: %0.0

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [29]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [01:13<00:00, 90.62it/s] 
100%|██████████| 835/835 [00:08<00:00, 103.19it/s]
100%|██████████| 836/836 [00:08<00:00, 128.13it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

Step1 using conv-layer- 5x5 of 16 filter
to generate low-level feature map of the given image
Step2 using max-pool-layer 2x2 stride (2,2)
to shrink the feature size by memorizing the highly activated features only.
step3 repeating the blocks of conv-layers, pooling
to adapt the new output changes and compining the knowledge to generate robust feature maps
step4 adding Global-Average-Pool-layer (GAP)
to flatten the output from the last block while keeping the feature location pattenrs the same.
step5 adding dense-softmax classifier
to make prediction of the 133-given dog classes.

In [46]:
from keras.layers import Conv2D, MaxPool2D, GlobalAvgPool2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense, Input
from keras.models import Model, Sequential


# in_shape, num_classes = (32, 32, 3), (10)
in_shape, num_classes = (224, 224, 3), 133
X = Input(shape=in_shape, name="Input")
conv1 = Conv2D(16, (5, 5), strides=(1, 1), activation="relu", name="conv1", padding="same")(X)
pool1 = MaxPool2D((2, 2), strides=(2, 2), name="pool1", padding="same")(conv1)
pool1 = Dropout(rate=0.2, name="dropped_pool1")(pool1)
#===== Conv 2 =====
conv2 = Conv2D(32, (3, 3), strides=(1, 1), activation="relu", name="conv2", padding="same")(pool1)
pool2 = MaxPool2D((2, 2), strides=(2, 2), name="pool2", padding="same")(conv2)
# pool2 = Dropout(rate=0.2, name="dropped_pool2")(pool2)
#===== Conv 3 =====
conv3 = Conv2D(64, (3, 3), strides=(1, 1), activation="relu", padding="same", name="conv3")(pool2)
pool3 = MaxPool2D((2, 2), strides=(1, 1), name="pool3", padding="same")(conv3)
pool3 = Dropout(rate=0.4, name="dropped_pool3")(pool3)
#===== Conv 4 =====
conv4 = Conv2D(128, kernel_size=(2, 2), strides=(1, 1), activation="relu", name="conv4", padding="same")(pool3)
pool4 = MaxPool2D((2, 2), strides=(2, 2), name="pool4", padding="same")(conv4)
pool4 = Dropout(rate=0.2, name="dropped_pool4")(pool4)
#===== Flatten =====
flatten_pool_3 = GlobalAvgPool2D()(pool4)
A1 = Dense(1024, activation="relu", name="H.L.1")(flatten_pool_3)
A1 = Dropout(rate=0.2, name="dropped_A1")(A1)
Y = Dense(num_classes, activation="softmax", name="Output")(A1)

### TODO: Define your architecture.
model = Model(X, Y)
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
Input (InputLayer)           (None, 224, 224, 3)       0         
_________________________________________________________________
conv1 (Conv2D)               (None, 224, 224, 16)      1216      
_________________________________________________________________
pool1 (MaxPooling2D)         (None, 112, 112, 16)      0         
_________________________________________________________________
dropped_pool1 (Dropout)      (None, 112, 112, 16)      0         
_________________________________________________________________
conv2 (Conv2D)               (None, 112, 112, 32)      4640      
_________________________________________________________________
pool2 (MaxPooling2D)         (None, 56, 56, 32)        0         
_________________________________________________________________
conv3 (Conv2D)               (None, 56, 56, 64)        18496     
_________________________________________________________________
pool3 (MaxPooling2D)         (None, 56, 56, 64)        0         
_________________________________________________________________
dropped_pool3 (Dropout)      (None, 56, 56, 64)        0         
_________________________________________________________________
conv4 (Conv2D)               (None, 56, 56, 128)       32896     
_________________________________________________________________
pool4 (MaxPooling2D)         (None, 28, 28, 128)       0         
_________________________________________________________________
dropped_pool4 (Dropout)      (None, 28, 28, 128)       0         
_________________________________________________________________
global_average_pooling2d_4 ( (None, 128)               0         
_________________________________________________________________
H.L.1 (Dense)                (None, 1024)              132096    
_________________________________________________________________
dropped_A1 (Dropout)         (None, 1024)              0         
_________________________________________________________________
Output (Dense)               (None, 133)               136325    
=================================================================
Total params: 325,669
Trainable params: 325,669
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [47]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [19]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 30

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8845 - acc: 0.0093Epoch 00001: val_loss improved from inf to 4.87484, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 36s 5ms/step - loss: 4.8846 - acc: 0.0093 - val_loss: 4.8748 - val_acc: 0.0108
Epoch 2/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8724 - acc: 0.0101Epoch 00002: val_loss improved from 4.87484 to 4.85661, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 34s 5ms/step - loss: 4.8722 - acc: 0.0100 - val_loss: 4.8566 - val_acc: 0.0168
Epoch 3/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.8154 - acc: 0.0168Epoch 00003: val_loss improved from 4.85661 to 4.77078, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 4.8151 - acc: 0.0168 - val_loss: 4.7708 - val_acc: 0.0216
Epoch 4/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.7300 - acc: 0.0219Epoch 00004: val_loss improved from 4.77078 to 4.73450, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 34s 5ms/step - loss: 4.7300 - acc: 0.0219 - val_loss: 4.7345 - val_acc: 0.0156
Epoch 5/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.6386 - acc: 0.0264Epoch 00005: val_loss improved from 4.73450 to 4.60660, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 4.6384 - acc: 0.0263 - val_loss: 4.6066 - val_acc: 0.0335
Epoch 6/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.5629 - acc: 0.0317Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 35s 5ms/step - loss: 4.5634 - acc: 0.0316 - val_loss: 4.6215 - val_acc: 0.0240
Epoch 7/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.5144 - acc: 0.0353Epoch 00007: val_loss improved from 4.60660 to 4.49150, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 4.5146 - acc: 0.0352 - val_loss: 4.4915 - val_acc: 0.0323
Epoch 8/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.4512 - acc: 0.0393- ETA: 1s - loss: 4Epoch 00008: val_loss improved from 4.49150 to 4.43907, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 34s 5ms/step - loss: 4.4518 - acc: 0.0394 - val_loss: 4.4391 - val_acc: 0.0383
Epoch 9/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.3707 - acc: 0.0488Epoch 00009: val_loss improved from 4.43907 to 4.32758, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 4.3710 - acc: 0.0488 - val_loss: 4.3276 - val_acc: 0.0503
Epoch 10/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.2650 - acc: 0.0568- ETA: 0s - loss: 4.2678 - acc:Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 34s 5ms/step - loss: 4.2636 - acc: 0.0569 - val_loss: 4.3449 - val_acc: 0.0491
Epoch 11/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.1844 - acc: 0.0629Epoch 00011: val_loss improved from 4.32758 to 4.29835, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 34s 5ms/step - loss: 4.1862 - acc: 0.0629 - val_loss: 4.2983 - val_acc: 0.0515
Epoch 12/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.1171 - acc: 0.0664Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 34s 5ms/step - loss: 4.1162 - acc: 0.0665 - val_loss: 4.3035 - val_acc: 0.0527
Epoch 13/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.0643 - acc: 0.0737Epoch 00013: val_loss improved from 4.29835 to 4.12670, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 4.0657 - acc: 0.0735 - val_loss: 4.1267 - val_acc: 0.0766
Epoch 14/30
6660/6680 [============================>.] - ETA: 0s - loss: 4.0222 - acc: 0.0814Epoch 00014: val_loss improved from 4.12670 to 4.11541, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 4.0216 - acc: 0.0813 - val_loss: 4.1154 - val_acc: 0.0766
Epoch 15/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.9525 - acc: 0.0869Epoch 00015: val_loss improved from 4.11541 to 4.07463, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 3.9519 - acc: 0.0870 - val_loss: 4.0746 - val_acc: 0.0623
Epoch 16/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.9135 - acc: 0.0953Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 35s 5ms/step - loss: 3.9137 - acc: 0.0951 - val_loss: 4.1519 - val_acc: 0.0671
Epoch 17/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.8740 - acc: 0.0992Epoch 00017: val_loss improved from 4.07463 to 4.01011, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 3.8734 - acc: 0.0993 - val_loss: 4.0101 - val_acc: 0.0766
Epoch 18/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.8183 - acc: 0.1077- ETA: 1s - loss: 3.819Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 34s 5ms/step - loss: 3.8170 - acc: 0.1075 - val_loss: 4.1516 - val_acc: 0.0683
Epoch 19/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.7820 - acc: 0.1072- ETA: 0s - loss: 3.7803 - acEpoch 00019: val_loss improved from 4.01011 to 3.94888, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 34s 5ms/step - loss: 3.7831 - acc: 0.1069 - val_loss: 3.9489 - val_acc: 0.0898
Epoch 20/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.7281 - acc: 0.1186Epoch 00020: val_loss improved from 3.94888 to 3.94334, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 3.7279 - acc: 0.1184 - val_loss: 3.9433 - val_acc: 0.0862
Epoch 21/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.7013 - acc: 0.1233Epoch 00021: val_loss improved from 3.94334 to 3.93724, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 34s 5ms/step - loss: 3.7010 - acc: 0.1237 - val_loss: 3.9372 - val_acc: 0.1006
Epoch 22/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.6477 - acc: 0.1320Epoch 00022: val_loss improved from 3.93724 to 3.81713, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 34s 5ms/step - loss: 3.6494 - acc: 0.1320 - val_loss: 3.8171 - val_acc: 0.1210
Epoch 23/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.6195 - acc: 0.1309Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 35s 5ms/step - loss: 3.6201 - acc: 0.1310 - val_loss: 3.9470 - val_acc: 0.0922
Epoch 24/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.5842 - acc: 0.1369Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 34s 5ms/step - loss: 3.5837 - acc: 0.1368 - val_loss: 3.8513 - val_acc: 0.0946
Epoch 25/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.5379 - acc: 0.1465Epoch 00025: val_loss improved from 3.81713 to 3.70123, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 3.5372 - acc: 0.1464 - val_loss: 3.7012 - val_acc: 0.1222
Epoch 26/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.5014 - acc: 0.1506Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 34s 5ms/step - loss: 3.5023 - acc: 0.1506 - val_loss: 3.7558 - val_acc: 0.1018
Epoch 27/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.4631 - acc: 0.1572Epoch 00027: val_loss improved from 3.70123 to 3.66799, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 34s 5ms/step - loss: 3.4637 - acc: 0.1572 - val_loss: 3.6680 - val_acc: 0.1281
Epoch 28/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.4228 - acc: 0.1626Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 34s 5ms/step - loss: 3.4231 - acc: 0.1626 - val_loss: 3.7939 - val_acc: 0.1150
Epoch 29/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.3948 - acc: 0.1665Epoch 00029: val_loss improved from 3.66799 to 3.63033, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 3.3952 - acc: 0.1660 - val_loss: 3.6303 - val_acc: 0.1317
Epoch 30/30
6660/6680 [============================>.] - ETA: 0s - loss: 3.3684 - acc: 0.1718Epoch 00030: val_loss improved from 3.63033 to 3.59728, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 35s 5ms/step - loss: 3.3688 - acc: 0.1723 - val_loss: 3.5973 - val_acc: 0.1569
Out[19]:
<keras.callbacks.History at 0x7fec07742940>

Load the Model with the Best Validation Loss

In [48]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [34]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 14.3541%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [35]:
bottleneck_features = np.load('/data/bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']
train_VGG16.shape, valid_VGG16.shape, test_VGG16.shape
Out[35]:
((6680, 7, 7, 512), (835, 7, 7, 512), (836, 7, 7, 512))

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [36]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 512)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [37]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [33]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6600/6680 [============================>.] - ETA: 0s - loss: 12.7691 - acc: 0.0982Epoch 00001: val_loss improved from inf to 11.54362, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 330us/step - loss: 12.7481 - acc: 0.0996 - val_loss: 11.5436 - val_acc: 0.1677
Epoch 2/20
6520/6680 [============================>.] - ETA: 0s - loss: 10.8963 - acc: 0.2379Epoch 00002: val_loss improved from 11.54362 to 10.81106, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 273us/step - loss: 10.9055 - acc: 0.2376 - val_loss: 10.8111 - val_acc: 0.2395
Epoch 3/20
6660/6680 [============================>.] - ETA: 0s - loss: 10.2268 - acc: 0.3021Epoch 00003: val_loss improved from 10.81106 to 10.41423, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 274us/step - loss: 10.2229 - acc: 0.3025 - val_loss: 10.4142 - val_acc: 0.2587
Epoch 4/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.7400 - acc: 0.3474Epoch 00004: val_loss improved from 10.41423 to 10.09733, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 266us/step - loss: 9.7451 - acc: 0.3470 - val_loss: 10.0973 - val_acc: 0.2850
Epoch 5/20
6560/6680 [============================>.] - ETA: 0s - loss: 9.5239 - acc: 0.3730Epoch 00005: val_loss improved from 10.09733 to 9.95116, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 261us/step - loss: 9.5236 - acc: 0.3731 - val_loss: 9.9512 - val_acc: 0.3126
Epoch 6/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.3525 - acc: 0.3874Epoch 00006: val_loss improved from 9.95116 to 9.85561, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 260us/step - loss: 9.3686 - acc: 0.3867 - val_loss: 9.8556 - val_acc: 0.3174
Epoch 7/20
6580/6680 [============================>.] - ETA: 0s - loss: 9.2182 - acc: 0.3997Epoch 00007: val_loss improved from 9.85561 to 9.75422, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 259us/step - loss: 9.1989 - acc: 0.4006 - val_loss: 9.7542 - val_acc: 0.3293
Epoch 8/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.0210 - acc: 0.4140Epoch 00008: val_loss improved from 9.75422 to 9.51502, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 259us/step - loss: 9.0158 - acc: 0.4144 - val_loss: 9.5150 - val_acc: 0.3353
Epoch 9/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.8709 - acc: 0.4325Epoch 00009: val_loss improved from 9.51502 to 9.47361, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 8.8894 - acc: 0.4310 - val_loss: 9.4736 - val_acc: 0.3449
Epoch 10/20
6540/6680 [============================>.] - ETA: 0s - loss: 8.7898 - acc: 0.4411Epoch 00010: val_loss improved from 9.47361 to 9.36336, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 262us/step - loss: 8.7996 - acc: 0.4406 - val_loss: 9.3634 - val_acc: 0.3629
Epoch 11/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.7504 - acc: 0.4476Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s 256us/step - loss: 8.7621 - acc: 0.4467 - val_loss: 9.3777 - val_acc: 0.3569
Epoch 12/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.7502 - acc: 0.4503Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 259us/step - loss: 8.7516 - acc: 0.4503 - val_loss: 9.3982 - val_acc: 0.3677
Epoch 13/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.7222 - acc: 0.4509Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 257us/step - loss: 8.7164 - acc: 0.4512 - val_loss: 9.3754 - val_acc: 0.3545
Epoch 14/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.6315 - acc: 0.4553Epoch 00014: val_loss improved from 9.36336 to 9.23236, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 257us/step - loss: 8.6345 - acc: 0.4551 - val_loss: 9.2324 - val_acc: 0.3737
Epoch 15/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.3644 - acc: 0.4633Epoch 00015: val_loss improved from 9.23236 to 8.98809, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 258us/step - loss: 8.3637 - acc: 0.4633 - val_loss: 8.9881 - val_acc: 0.3820
Epoch 16/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.2543 - acc: 0.4795Epoch 00016: val_loss improved from 8.98809 to 8.94899, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 259us/step - loss: 8.2269 - acc: 0.4811 - val_loss: 8.9490 - val_acc: 0.3892
Epoch 17/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.1961 - acc: 0.4869Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s 258us/step - loss: 8.2095 - acc: 0.4861 - val_loss: 8.9723 - val_acc: 0.3904
Epoch 18/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.1662 - acc: 0.4887Epoch 00018: val_loss improved from 8.94899 to 8.89669, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 260us/step - loss: 8.1653 - acc: 0.4888 - val_loss: 8.8967 - val_acc: 0.3880
Epoch 19/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.0990 - acc: 0.4914Epoch 00019: val_loss improved from 8.89669 to 8.85988, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 259us/step - loss: 8.0873 - acc: 0.4921 - val_loss: 8.8599 - val_acc: 0.3880
Epoch 20/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.0301 - acc: 0.4955Epoch 00020: val_loss improved from 8.85988 to 8.85757, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 261us/step - loss: 8.0473 - acc: 0.4945 - val_loss: 8.8576 - val_acc: 0.3880
Out[33]:
<keras.callbacks.History at 0x7fec1c628a90>

Load the Model with the Best Validation Loss

In [38]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [39]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 40.1914%

Predict Dog Breed with the Model

In [80]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras. These are already in the workspace, at /data/bottleneck_features. If you wish to download them on a different machine, they can be found at:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception.

The above architectures are downloaded and stored for you in the /data/bottleneck_features/ folder.

This means the following will be in the /data/bottleneck_features/ folder:

DogVGG19Data.npz DogResnet50Data.npz DogInceptionV3Data.npz DogXceptionData.npz

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('/data/bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [50]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('/data/bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test']
print(f"training features size: {train_Xception.shape}, train targets size: {train_targets.shape}")
print(f"training features size: {valid_Xception.shape}, train targets size: {valid_targets.shape}")
print(f"training features size: {test_Xception.shape}, train targets size: {test_targets.shape}")
training features size: (6680, 7, 7, 2048), train targets size: (6680, 133)
training features size: (835, 7, 7, 2048), train targets size: (835, 133)
training features size: (836, 7, 7, 2048), train targets size: (836, 133)

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer: Xception network has the highst accuracy against all other networks on ImageNet data.

step1: defining the output shape of the bottleneck features preload on the Xception network as new input to a new classification model.
step2: adding GAP layer to the output to flatten the images to match the one hot encoded ouput classes vector
step3: adding a dense layer of softmax activation layer working as a categorical classifier as output.

In [16]:
### TODO: Define your architecture.
from keras.layers import GlobalAvgPool2D
from keras.layers import Dense, Input
from keras.models import Model

pretrained_shape = (7, 7, 2048)  # train_Xception.shape[1:]
# xception_model = Xception(input_shape=pretrained_shape, weighs='imagenet', include_top=False)
X = Input(shape=pretrained_shape)
gap = GlobalAvgPool2D()(X)
Y = Dense(133, activation='softmax')(gap)
model = Model(X, Y)
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_2 (InputLayer)         (None, 7, 7, 2048)        0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 2048)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [17]:
### TODO: Compile the model.
from keras.callbacks import ModelCheckpoint  
from keras.preprocessing.image import ImageDataGenerator
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [65]:
### TODO: Train the model.
epochs = 30
batch_size = 32
steps_per_epoch = train_Xception.shape[0] // batch_size
val_steps = valid_Xception.shape[0] // batch_size
Xception_weights = 'saved_models/Xception_weights.best.from_scratch.hdf5'
imagegen = ImageDataGenerator\
(
    rescale= 1./255, 
    rotation_range= 30,  # random image rotation from (0 : input_choice)
    width_shift_range= 0.1,  # random horizontal shift
    height_shift_range= 0.1, # random Vertical shift
    horizontal_flip= True,
    shear_range = 0.3, 
    zoom_range = 0.3, 
    fill_mode = "nearest",  # set mode for filling points outside input boundaries
)

train_batch = imagegen.flow(train_Xception, train_targets, batch_size=32)
val_batch = imagegen.flow(valid_Xception, valid_targets, batch_size=32)
test_batch = imagegen.flow(test_Xception, test_targets, batch_size=32)
    
checkpointer = ModelCheckpoint(filepath=Xception_weights, verbose=1, save_best_only=True)

history = model.fit_generator(
    train_batch, steps_per_epoch=steps_per_epoch, validation_data=val_batch, 
    validation_steps=val_steps, epochs=epochs, callbacks=[checkpointer], verbose=1)
/opt/conda/lib/python3.6/site-packages/keras/preprocessing/image.py:855: UserWarning: NumpyArrayIterator is set to use the data format convention "channels_last" (channels on axis 3), i.e. expected either 1, 3 or 4 channels on axis 3. However, it was passed an array with shape (6680, 7, 7, 2048) (2048 channels).
  ' (' + str(self.x.shape[channels_axis]) + ' channels).')
/opt/conda/lib/python3.6/site-packages/keras/preprocessing/image.py:855: UserWarning: NumpyArrayIterator is set to use the data format convention "channels_last" (channels on axis 3), i.e. expected either 1, 3 or 4 channels on axis 3. However, it was passed an array with shape (835, 7, 7, 2048) (2048 channels).
  ' (' + str(self.x.shape[channels_axis]) + ' channels).')
/opt/conda/lib/python3.6/site-packages/keras/preprocessing/image.py:855: UserWarning: NumpyArrayIterator is set to use the data format convention "channels_last" (channels on axis 3), i.e. expected either 1, 3 or 4 channels on axis 3. However, it was passed an array with shape (836, 7, 7, 2048) (2048 channels).
  ' (' + str(self.x.shape[channels_axis]) + ' channels).')
Epoch 1/30
207/208 [============================>.] - ETA: 1s - loss: 4.8258 - acc: 0.3172Epoch 00001: val_loss improved from inf to 4.76065, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 523s 3s/step - loss: 4.8254 - acc: 0.3179 - val_loss: 4.7606 - val_acc: 0.4760
Epoch 2/30
207/208 [============================>.] - ETA: 1s - loss: 4.6956 - acc: 0.4821Epoch 00002: val_loss improved from 4.76065 to 4.63231, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 495s 2s/step - loss: 4.6953 - acc: 0.4819 - val_loss: 4.6323 - val_acc: 0.5252
Epoch 3/30
207/208 [============================>.] - ETA: 1s - loss: 4.5704 - acc: 0.5413Epoch 00003: val_loss improved from 4.63231 to 4.51039, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 505s 2s/step - loss: 4.5702 - acc: 0.5415 - val_loss: 4.5104 - val_acc: 0.5288
Epoch 4/30
207/208 [============================>.] - ETA: 1s - loss: 4.4451 - acc: 0.5784Epoch 00004: val_loss improved from 4.51039 to 4.39763, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 503s 2s/step - loss: 4.4446 - acc: 0.5789 - val_loss: 4.3976 - val_acc: 0.5817
Epoch 5/30
207/208 [============================>.] - ETA: 1s - loss: 4.3248 - acc: 0.6026Epoch 00005: val_loss improved from 4.39763 to 4.27860, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 500s 2s/step - loss: 4.3243 - acc: 0.6032 - val_loss: 4.2786 - val_acc: 0.5853
Epoch 6/30
207/208 [============================>.] - ETA: 1s - loss: 4.2015 - acc: 0.6204Epoch 00006: val_loss improved from 4.27860 to 4.15892, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 502s 2s/step - loss: 4.2015 - acc: 0.6201 - val_loss: 4.1589 - val_acc: 0.6022
Epoch 7/30
207/208 [============================>.] - ETA: 1s - loss: 4.0838 - acc: 0.6373Epoch 00007: val_loss improved from 4.15892 to 4.05207, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 500s 2s/step - loss: 4.0839 - acc: 0.6371 - val_loss: 4.0521 - val_acc: 0.6070
Epoch 8/30
207/208 [============================>.] - ETA: 1s - loss: 3.9701 - acc: 0.6505Epoch 00008: val_loss improved from 4.05207 to 3.94032, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 503s 2s/step - loss: 3.9698 - acc: 0.6506 - val_loss: 3.9403 - val_acc: 0.6178
Epoch 9/30
207/208 [============================>.] - ETA: 1s - loss: 3.8556 - acc: 0.6566Epoch 00009: val_loss improved from 3.94032 to 3.80082, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 496s 2s/step - loss: 3.8550 - acc: 0.6562 - val_loss: 3.8008 - val_acc: 0.6671
Epoch 10/30
207/208 [============================>.] - ETA: 1s - loss: 3.7406 - acc: 0.6724Epoch 00010: val_loss improved from 3.80082 to 3.71809, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 503s 2s/step - loss: 3.7402 - acc: 0.6728 - val_loss: 3.7181 - val_acc: 0.6406
Epoch 11/30
207/208 [============================>.] - ETA: 1s - loss: 3.6317 - acc: 0.6823Epoch 00011: val_loss improved from 3.71809 to 3.60901, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 504s 2s/step - loss: 3.6314 - acc: 0.6824 - val_loss: 3.6090 - val_acc: 0.6587
Epoch 12/30
207/208 [============================>.] - ETA: 1s - loss: 3.5191 - acc: 0.6942Epoch 00012: val_loss improved from 3.60901 to 3.49725, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 503s 2s/step - loss: 3.5189 - acc: 0.6945 - val_loss: 3.4973 - val_acc: 0.6875
Epoch 13/30
207/208 [============================>.] - ETA: 1s - loss: 3.4142 - acc: 0.7019Epoch 00013: val_loss improved from 3.49725 to 3.41209, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 499s 2s/step - loss: 3.4136 - acc: 0.7020 - val_loss: 3.4121 - val_acc: 0.6647
Epoch 14/30
207/208 [============================>.] - ETA: 1s - loss: 3.3151 - acc: 0.7064Epoch 00014: val_loss improved from 3.41209 to 3.29244, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 498s 2s/step - loss: 3.3150 - acc: 0.7069 - val_loss: 3.2924 - val_acc: 0.6983
Epoch 15/30
207/208 [============================>.] - ETA: 1s - loss: 3.2037 - acc: 0.7191Epoch 00015: val_loss improved from 3.29244 to 3.16646, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 503s 2s/step - loss: 3.2038 - acc: 0.7180 - val_loss: 3.1665 - val_acc: 0.6995
Epoch 16/30
207/208 [============================>.] - ETA: 1s - loss: 3.1000 - acc: 0.7198Epoch 00016: val_loss improved from 3.16646 to 3.08806, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 503s 2s/step - loss: 3.1001 - acc: 0.7191 - val_loss: 3.0881 - val_acc: 0.7007
Epoch 17/30
207/208 [============================>.] - ETA: 1s - loss: 3.0081 - acc: 0.7282Epoch 00017: val_loss improved from 3.08806 to 3.00860, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 499s 2s/step - loss: 3.0082 - acc: 0.7281 - val_loss: 3.0086 - val_acc: 0.7103
Epoch 18/30
207/208 [============================>.] - ETA: 1s - loss: 2.9049 - acc: 0.7312Epoch 00018: val_loss improved from 3.00860 to 2.91473, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 501s 2s/step - loss: 2.9056 - acc: 0.7311 - val_loss: 2.9147 - val_acc: 0.6827
Epoch 19/30
207/208 [============================>.] - ETA: 1s - loss: 2.8190 - acc: 0.7303Epoch 00019: val_loss improved from 2.91473 to 2.79021, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 499s 2s/step - loss: 2.8188 - acc: 0.7309 - val_loss: 2.7902 - val_acc: 0.7308
Epoch 20/30
207/208 [============================>.] - ETA: 1s - loss: 2.7261 - acc: 0.7385Epoch 00020: val_loss improved from 2.79021 to 2.72974, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 501s 2s/step - loss: 2.7265 - acc: 0.7384 - val_loss: 2.7297 - val_acc: 0.7248
Epoch 21/30
207/208 [============================>.] - ETA: 1s - loss: 2.6345 - acc: 0.7473Epoch 00021: val_loss improved from 2.72974 to 2.63541, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 498s 2s/step - loss: 2.6346 - acc: 0.7470 - val_loss: 2.6354 - val_acc: 0.7368
Epoch 22/30
207/208 [============================>.] - ETA: 1s - loss: 2.5458 - acc: 0.7481Epoch 00022: val_loss improved from 2.63541 to 2.58323, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 498s 2s/step - loss: 2.5457 - acc: 0.7480 - val_loss: 2.5832 - val_acc: 0.7115
Epoch 23/30
207/208 [============================>.] - ETA: 1s - loss: 2.4542 - acc: 0.7514Epoch 00023: val_loss improved from 2.58323 to 2.44342, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 493s 2s/step - loss: 2.4538 - acc: 0.7517 - val_loss: 2.4434 - val_acc: 0.7488
Epoch 24/30
207/208 [============================>.] - ETA: 1s - loss: 2.3941 - acc: 0.7533Epoch 00024: val_loss improved from 2.44342 to 2.39550, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 499s 2s/step - loss: 2.3935 - acc: 0.7532 - val_loss: 2.3955 - val_acc: 0.7091
Epoch 25/30
207/208 [============================>.] - ETA: 1s - loss: 2.2963 - acc: 0.7620Epoch 00025: val_loss improved from 2.39550 to 2.34086, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 498s 2s/step - loss: 2.2953 - acc: 0.7625 - val_loss: 2.3409 - val_acc: 0.7260
Epoch 26/30
207/208 [============================>.] - ETA: 1s - loss: 2.2289 - acc: 0.7586Epoch 00026: val_loss improved from 2.34086 to 2.24023, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 498s 2s/step - loss: 2.2291 - acc: 0.7586 - val_loss: 2.2402 - val_acc: 0.7260
Epoch 27/30
207/208 [============================>.] - ETA: 1s - loss: 2.1546 - acc: 0.7599Epoch 00027: val_loss improved from 2.24023 to 2.20085, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 500s 2s/step - loss: 2.1537 - acc: 0.7602 - val_loss: 2.2008 - val_acc: 0.7272
Epoch 28/30
207/208 [============================>.] - ETA: 1s - loss: 2.0784 - acc: 0.7709Epoch 00028: val_loss improved from 2.20085 to 2.11461, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 503s 2s/step - loss: 2.0796 - acc: 0.7704 - val_loss: 2.1146 - val_acc: 0.7596
Epoch 29/30
207/208 [============================>.] - ETA: 1s - loss: 2.0248 - acc: 0.7675Epoch 00029: val_loss improved from 2.11461 to 2.02804, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 501s 2s/step - loss: 2.0239 - acc: 0.7682 - val_loss: 2.0280 - val_acc: 0.7392
Epoch 30/30
207/208 [============================>.] - ETA: 1s - loss: 1.9508 - acc: 0.7741Epoch 00030: val_loss improved from 2.02804 to 2.00580, saving model to saved_models/Xception_weights.best.from_scratch.hdf5
208/208 [==============================] - 501s 2s/step - loss: 1.9507 - acc: 0.7746 - val_loss: 2.0058 - val_acc: 0.7476
In [67]:
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()

# Plot training & validation loss values
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [18]:
### TODO: Load the model weights with the best validation loss.
Xception_weights = 'saved_models/Xception_weights.best.from_scratch.hdf5'
model.load_weights(Xception_weights)

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [73]:
### TODO: Calculate classification accuracy on the test dataset.
test_steps = test_Xception.shape[0] // batch_size
Xception_preds = [np.argmax(model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]
_, acc = model.evaluate_generator(test_batch, steps=test_steps)
print('Test accuracy: %.4f%%' % acc)
Test accuracy: 0.7668%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [19]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from keras.applications.resnet50 import preprocess_input, decode_predictions
from extract_bottleneck_features import extract_Xception
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)


def predict_dog_preed(img_path):
    img_tensor = path_to_tensor(img_path)
    procc_img = preprocess_input(img_tensor)
    features = extract_Xception(procc_img)
    class_index = np.argmax(model.predict(features))
    dir_name = dog_names[class_index]
    name_1st_index = dir_name.index(".") + 1
    return dog_names[class_index][name_1st_index:]

Testing model prediction

In [110]:
test_img = dog_files_short[55]
print(test_img)
predict_dog_preed(test_img)
/data/dog_images/train/019.Bedlington_terrier/Bedlington_terrier_01374.jpg
dir name:  in/019.Bedlington_terrier
Out[110]:
'Bedlington_terrier'
In [111]:
test_img = human_files[55]
predict_dog_preed(test_img)
dir name:  in/049.Chinese_crested
Out[111]:
'Chinese_crested'

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [20]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
def preed_similarity(img_path):
    Xception_weights = 'saved_models/Xception_weights.best.from_scratch.hdf5'
    model.load_weights(Xception_weights)
    class_name = predict_dog_preed(img_path)
    isdog = dog_detector(img_path)
    ishuman = my_face_detector(img_path)
    if isdog:
        return 0, class_name
    elif ishuman or ishuman and isdog:
        return 1, class_name
    else:
        print("Input image couldn't be recognised as known class!")

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: the output works better than I expected relative to the accuracy. improving the model may come with:

  • training the model with more epochs to get higher accuracy.
  • using better detection algorithm than the HOG and cropping the dog, human faces and classify them separately.
  • adding l1 regulizer, dropouts to the output model with one dense layer.
  • training on more images.
In [21]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array, array_to_img 
%config InlineBackend.figure_format = 'retina'
%matplotlib inline                               

test_imgs = [img_path for img_path in glob("testimgs/*")]

def plot_imgs_row(imgs_path, n_by_row=4):
    n_imgs = len(imgs_path)
    dog_message = "nice dog"
    human_message = "looking for preed matches you\n"
    fig = plt.figure(figsize=(15, 19), dpi=100)
    for i in tqdm(range(n_imgs)):
        img_path = test_imgs[i]
        Class, preed = preed_similarity(img_path)
        if Class:
            title = human_message  
            footer = "you better own: {}!".format(preed)
        else: 
            title = dog_message
            footer = "detected preed: {}".format(preed)
        img = plt.imread(img_path)
        ax = fig.add_subplot((n_imgs // n_by_row) + 1, n_by_row, i+1)
        ax.get_yaxis().set_visible(False)
        ax.set_title(title, fontsize=12)
        ax.set_xlabel(footer, fontsize=11)
        ax.set_xticks([])
        ax.imshow(img)
In [22]:
batch1 = test_imgs
plot_imgs_row(batch1)
  0%|          | 0/12 [00:00<?, ?it/s]
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.4/xception_weights_tf_dim_ordering_tf_kernels_notop.h5
83689472/83683744 [==============================] - 1s 0us/step
100%|██████████| 12/12 [01:20<00:00,  7.31s/it]
In [86]:
import cv2
import dlib
from io import BytesIO
import numpy as np
from PIL import Image
from keras.preprocessing.image import img_to_array, array_to_img 
%matplotlib inline    
%config InlineBackend.figure_format = 'retina'
                           

def mask_nose(img_arr, nose_arr):
    pt1, pt2, w, h = get_nose_box()
    p_img = array_to_img(img_arr)
    p_nose = array_to_img(nose_arr)
    p_nose = p_nose.resize((int(w), int(h)))
    p_img.paste(p_nose, pt1)
    p_img = img_to_array(p_img).astype(dtype="uint8")
    return p_img


def get_nose_box():
    x1 = landmarks.part(31).x - 30
    y1 = landmarks.part(28).y + 5
    x2 = landmarks.part(35).x + 10
    y2 = landmarks.part(33).y
    w, h = x2 - x1, y2 - y1
    return (x1, y1), (x2, y2), w * 1.5, h * 1.5


f_detector = dlib.get_frontal_face_detector()
f_predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
img_path = test_imgs[6]
img_arr = cv2.imread(img_path)
nose_arr = cv2.imread("nose.png")
faces = f_detector(img_arr)

for face in faces:
    landmarks = f_predictor(img_arr, face)
    img_arr = mask_nose(img_arr, nose_arr)
    pt1 = (face.left(), face.top())
    pt2 = (face.right(), face.bottom())
    
#     cv2.rectangle(img, pt1, pt2, color=(0, 255, 0), thickness=3)

Class, preed = preed_similarity(img_path)
dog_message = "nice dog"
human_message = "wondered what preed would match you!\n"

if Class:
    title = human_message  
    footer = "you better own: {}!".format(preed)
else: 
    title = dog_message
    footer = "detected preed: {}".format(preed)
    
img_arr = cv2.cvtColor(img_arr, cv2.COLOR_BGR2RGB)
plt.imshow(img_arr)
plt.xticks([], [])
plt.yticks([], [])
plt.title(title, fontsize=12)
plt.xlabel(footer, fontsize=14)
Out[86]:
Text(0.5,0,'you better own: Chinese_crested!')

Please download your notebook to submit

In order to submit, please do the following:

  1. Download an HTML version of the notebook to your computer using 'File: Download as...'
  2. Click on the orange Jupyter circle on the top left of the workspace.
  3. Navigate into the dog-project folder to ensure that you are using the provided dog_images, lfw, and bottleneck_features folders; this means that those folders will not appear in the dog-project folder. If they do appear because you downloaded them, delete them.
  4. While in the dog-project folder, upload the HTML version of this notebook you just downloaded. The upload button is on the top right.
  5. Navigate back to the home folder by clicking on the two dots next to the folder icon, and then open up a terminal under the 'new' tab on the top right
  6. Zip the dog-project folder with the following command in the terminal: zip -r dog-project.zip dog-project
  7. Download the zip file by clicking on the square next to it and selecting 'download'. This will be the zip file you turn in on the next node after this workspace!